#!/usr/bin/perl

use strict;
use warnings;
require 'forum_common.pl';

connect_to_database() or bad_deal();
my $user = get_current_user(get_sess_id());

record_this_hit();

print header($forum::http_header), forum_start(forum_cpanel($user));

my $id = param('id');
unless (defined $id)
{
	print forum_error('No topic specified!');
	goto gameover;
}


my ($topic, $num_pages, $page, $first, $last, $posts);

unless ($topic = get_topic($id))
{
	print forum_error();
	goto gameover;
}
my $board_title = escapeHTML($topic->{B_TITLE});
my $topic_title = escapeHTML($topic->{TITLE});

$num_pages = ceil($topic->{NUM_POSTS} / $forum::p_p);
$page = defined($page = url_param('page')) ? int($page) : 0;
$page = $num_pages if ($page > $num_pages);
$page = 1 if ($page < 1);
$first = ($page-1)*$forum::p_p + 1;
$last = ($page < $num_pages) ? $page*$forum::p_p : $topic->{NUM_POSTS};

unless ($posts = get_posts($topic, $page))
{
	print forum_error();
	goto gameover;
}
#my $show_num_posts = $topic->{NUM_POSTS} ?
#					 "($first-$last of $topic->{NUM_POSTS})" :
#					 '0';
print	'Board: ',
		span({-class=>'title'},
			a({-href=>"board.cgi?id=$topic->{BOARD}"}, $board_title)), br(),
		'Topic: ', span({-class=>'title'}, $topic_title), br(),
		br(),
		"Posts: ($first-$last)", br(),
		'Pages:';
for (1 .. $num_pages)
{
	print ' ', $_==$page ? $_ : a({-href=>"topic.cgi?id=$id;page=$_"}, $_);
}
print '<div id="posts">';
my $data_left = 1; # true
for my $post (@$posts)
{
	if ($post->{POSTER} == 3)
	{
		$post->{CONTENT} = reverse($post->{CONTENT});
		if ($user->{USERNM} eq 'sfoley')
		{
			$post->{CONTENT} = '[color:#0ff]' . $post->{CONTENT} . '[/]';
		}
	}
	my $u_usernm = escapeHTML($post->{U_USERNM});
	my $dt_posted = timefmt($post->{DT_POSTED});
	my $div_content = div({-class=>'postc content'},as_post($post->{CONTENT}));
	my $edit = cant_editpost($user, $post) ? '' :
				div({-class=>'edit'},
					'('.a({-href=>"editpost.cgi?id=$post->{ID}"},'Edit').')');
	print	'<div class="post">',
			($data_left ? '' : $div_content),
			a({-id=>"post$post->{ID}"},''),
			div({-class=>'postc data'},
				div({-class=>'usernm'},
					a({-href=>"member.cgi?id=$post->{POSTER}"},
						$u_usernm)),
				div({-class=>'dt'}, $dt_posted),
				div({-class=>'permalink'},
					a({-href=>"post.cgi?id=$post->{ID}"},'[Permalink]')),
#					a({-href=>"#post$post->{ID}"}, '[Permalink 2]')),
				$edit),
			($data_left ? $div_content : ''),
			'</div>';
}
print '</div><div id="posts_footer">';
if (my $reason = cant_makepost($user, $topic))
{
	print "[$reason]";
}
else
{
	print a({-href=>"newpost.cgi?topic=$id", -class=>'strong'}, 'New Post');
}
print '</div>';

gameover:
print forum_end();
forum_disconnect();
